<template>
  <div class="user-info-table">
    <!-- 顶部搜索栏 -->
    <el-row class="search-bar" style="margin-bottom: 20px; background-color: #fff; padding: 15px;">
      <el-col :span="24">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="昵称">
            <el-input v-model="searchForm.nickName" placeholder="请输入昵称"></el-input>
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="searchForm.phone" placeholder="请输入手机号"></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态">
              <el-option label="正常" :value="1"></el-option>
              <el-option label="封禁" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchUsers">查询</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table
      :data="userList"
      style="width: 100%"
      :border="true" 
      stripe
      :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
    >
      <!-- 用户ID -->
      <el-table-column prop="id" label="用户ID" width="200"></el-table-column>

      <!-- 昵称 -->
      <el-table-column prop="nickName" label="昵称" width="250"></el-table-column>

      <!-- 手机号 -->
      <el-table-column prop="phone" label="手机号" width="300"></el-table-column>

      <!-- 积分 -->
      <el-table-column prop="point" label="积分" width="200">
        <template #default="scope">
          {{ scope.row.point || 0 }}
        </template>
      </el-table-column>

        <!-- 状态 -->
        <el-table-column prop="status" label="状态" width="200">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '正常' : '封禁' }}
          </el-tag>
        </template>
      </el-table-column>

        <!-- 操作 -->
        <el-table-column label="操作" width="300" fixed="right">
        <template #default="scope">
          <el-button 
            :type="scope.row.status === 1 ? 'danger' : 'success'"
            size="small" 
            @click="handleBanUser(scope.row)"
          >{{ scope.row.status === 1 ? '封禁' : '解封' }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container" style="margin-top: 20px; text-align: center;">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :current-page="pageNum"
        :page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>

    <!-- 修改积分对话框 -->
    <el-dialog 
      title="修改用户积分" 
      :visible.sync="pointsDialogVisible"
      width="30%"
    >
      <el-form :model="pointsForm" ref="pointsFormRef" :rules="pointsRules">
        <el-form-item label="成交金额" prop="totalAmount">
          <el-input v-model.number="pointsForm.totalAmount" type="number"></el-input>
        </el-form-item>
        <el-form-item label="订单完成状态" prop="type">
          <el-select v-model="pointsForm.type" placeholder="请选择状态">
            <el-option label="未完成" :value="0"></el-option>
            <el-option label="已完成" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="pointsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitPointsEdit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      // 搜索表单
      searchForm: {
        id: '',
        nickName: '',
        phone: '',
        status: ''
      },
      // 表格数据
      userList: [],
      // 分页
      total: 0,
      pageNum: 1,
      pageSize: 10,
      // 积分修改对话框
      pointsDialogVisible: false,
      pointsForm: {
        id: '',
        totalAmount: 0,
        type: 0
      },
      // 积分表单验证规则
      pointsRules: {
        totalAmount: [
          { required: true, message: '请输入成交金额', trigger: 'blur' },
          { type: 'number', message: '金额必须为数字' }
        ],
        type: [
          { required: true, message: '请选择订单完成状态', trigger: 'change' }
        ]
      },
      loading: false
    };
  },
  methods: {
    // 修改查询用户列表方法
    searchUsers() {
      this.loading = true; // 开始加载
      // 构建查询参数
      const params = new URLSearchParams();
      
      // 只有当值不为空时才添加参数
      if (this.searchForm.id) {
        params.append('id', this.searchForm.id);
      }
      if (this.searchForm.nickName) {
        params.append('nickName', this.searchForm.nickName);
      }
      if (this.searchForm.phone) {
        params.append('phone', this.searchForm.phone);
      }
      if (this.searchForm.status !== '') {
        params.append('status', this.searchForm.status);
      }
      
      // 添加分页参数
      params.append('pageNum', this.pageNum);
      params.append('pageSize', this.pageSize);

      console.log('发送请求参数:', params.toString()); // 添加调试日志

      axios.get('/zsd-user/user-info/selUser', {
        params: params
      }).then(response => {
        console.log('收到响应:', response.data);
        if (response.data.code === 200) {
          const data = response.data.data;
          console.log('处理后的数据:', data);
          this.userList = data.list || []; // 修改为使用list字段
          this.total = data.total || 0;
          console.log('更新后的userList:', this.userList);
        } else {
          this.$message.error(response.data.msg || '查询失败');
        }
      }).catch(error => {
        console.error('查询失败', error);
        this.$message.error('查询失败');
      }).finally(() => {
        this.loading = false; // 结束加载
      });
    },

    // 处理分页大小变化
    handleSizeChange(val) {
      this.pageSize = val;
      this.searchUsers();
    },

    // 处理页码变化
    handleCurrentChange(val) {
      this.pageNum = val;
      this.searchUsers();
    },

    // 打开修改积分对话框
    handleEditPoints(row) {
      this.pointsForm.id = row.id;
      this.pointsForm.totalAmount = 0;
      this.pointsForm.type = 0;
      this.pointsDialogVisible = true;
    },

    // 提交积分修改
    submitPointsEdit() {
      this.$refs.pointsFormRef.validate((valid) => {
        if (valid) {
          axios({
            method: 'put',
            url: '/zsd-user/user-info/addPointById',
            data: this.pointsForm,
            headers: {
              'Content-Type': 'application/json'
            }
          }).then(response => {
            if (response.data.code === 200) {
              this.$message.success('修改成功');
              this.pointsDialogVisible = false;
              this.searchUsers();
            } else {
              this.$message.error(response.data.msg || '修改失败');
            }
          }).catch(error => {
            console.error('修改失败', error);
            this.$message.error('修改失败');
          });
        }
      });
    },

    // 处理封禁/解封
    handleBanUser(row) {
      const action = row.status === 1 ? '封禁' : '解封';
      this.$confirm(`确定要${action}该用户吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios({
          method: 'put',
          url: '/zsd-user/user/banUser',
          params: {
            id: row.id
          },
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        }).then(response => {
          if (response.data.code === 200) {
            this.$message.success(`${action}成功`);
            this.searchUsers();
          } else {
            this.$message.error(response.data.msg || `${action}失败`);
          }
        }).catch(error => {
          console.error(`${action}失败`, error);
          this.$message.error(`${action}失败`);
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    }
  },
  created() {
    this.searchUsers();
  }
};
</script>

<style scoped>
.pagination-container {
  margin-top: 20px;
  text-align: center;
}

/* 设置表头样式 */
.el-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  height: 48px;
  line-height: 48px;
}

/* 设置行高 */
.el-table__row {
  height: 48px;
  line-height: 48px;
}

/* 设置单元格样式 */
.el-table .cell {
  padding: 0 10px; /* 添加左右内边距 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 用于特定列的文本溢出省略号 */
.ellipsis {
  display: inline-block;
  max-width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 自定义搜索栏样式 */
.search-bar {
  border-bottom: 1px solid #ebeef5;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 15px;
  background-color: #fff;
}

/* 自定义 el-form-item 样式 */
.demo-form-inline .el-form-item {
  margin-bottom: 0;
}

/* 自定义 el-input 和 el-select 样式 */
.demo-form-inline .el-input, .demo-form-inline .el-select {
  width: 200px;
}
</style>